package com.example.main;

import org.apache.commons.lang3.time.StopWatch;

import java.util.Random;
import java.util.concurrent.*;

public class Main09 {
    public static ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 2,
            2, TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>(1000),new ThreadPoolExecutor.CallerRunsPolicy());

    public static void main(String[] args) {
//        SynchronousQueue<Boolean> queue = new SynchronousQueue<>();
        BlockingDeque<Boolean> queue =new LinkedBlockingDeque<>();
        StopWatch stopWatch=new StopWatch();
        stopWatch.start();
        int num=1;
        int total=1;
        for (int i = 0; i < 10; i++) {
            executor.execute(new Task(queue));
            total++;
        }
        while (total!=num){
            try {
                queue.take();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("第 "+num+" 次");
            num++;
        }
        executor.shutdown();
        System.out.println("queue = " + queue.size());
        System.out.println("执行结束,耗时: "+stopWatch.getTime());
        stopWatch.stop();
    }

    public static class Task implements Runnable{
        private final BlockingDeque<Boolean> queue;

        public Task(BlockingDeque<Boolean> queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            try {
                int i = new Random().nextInt(5);
                System.out.println("i = " + i);
                TimeUnit.SECONDS.sleep(i);
                queue.put(true);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
